import { useEffect, useState, useRef } from 'react'

function Demo1() {
  const [flag, setFlag] = useState(true)

  return (
    <div>
      <h1>父组件</h1>
      <button onClick={() => setFlag(!flag)}>Toggle</button>
      <hr />

      {flag && <Son />}
    </div>
  )
}

function Son() {
  const timer = useRef(null)

  useEffect(() => {
    timer.current = setInterval(() => {
      console.log('ok')
    }, 1000)

    // 清理函数的执行时机：当组件被销毁的时候，执行清理函数
    return () => {
      console.log('执行了清理函数')
      clearInterval(timer.current)
    }
  }, [])

  return (
    <div>
      <h3>子组件</h3>
    </div>
  )
}

export default Demo1
